package org.arithmetic.array;

import java.util.Scanner;

/**
 * Created by LUOLIANG on 2016/9/2.
 * 打印一个蛇形矩阵
 */
public class Matrix {

    //蛇形矩阵
    public static int[][] snakeMatrix(int n) {
        int arr[][] = new int[n][n];

        //给每个元素赋值
        int k = 1;
        for (int i = 0; i < n; i++) {
            int t = i;
            for (int j = 0; j <= i; j++) {
                arr[t][j] = k;
                k++;
                t--;
            }
        }

        return arr;
    }

    //顺时针回形矩阵
    public static int[][] returnMatrix(int n) {
        int arr[][] = new int[n][n];
        int k = 1;
        int x = 0, y = 0;
        int xMax = n, yMax = n;
        int xMin = 0, yMin = 0;
        boolean flag = true;

        for (int i = 0; i < n * n; i++) {
            arr[x][y] = k;
            k++;

            //逻辑开始
            if (y + 1 < yMax && flag) {
                y++;
            } else if (x + 1 < xMax && flag) {
                x++;
            } else {
                if (y > yMin) {
                    y--;
                } else if (x > xMin + 1) {
                    x--;
                } else {
                    xMax--;
                    yMax--;
                    xMin++;
                    yMin++;
                    y++;
                    flag = true;
                }
            }

            if ((x + 1) == xMax && (y + 1) == yMax) {
                flag = false;
            }
        }

        return arr;
    }

    //用于打印二维数组
    public static void displayMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] != 0) System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入N：");
        while (input.hasNext()) {
            int N = input.nextInt();
            int a1[][] = snakeMatrix(N);
            int a2[][] = returnMatrix(N);

            displayMatrix(a1);
            displayMatrix(a2);
        }
    }
}
